$(document).ready(function() {
//	$("#t_devis img[title]").tooltip();
	$("#creer_facture_tabs").tabs();
	$("#newFactureOK_dial").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		buttons: {
			"Fermer": function (){
				window.location = "/achats?factures";
			}
		}
		
	});
	$("#new_facture_dial").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		width: '1000',
		height: '700',
		buttons: {
			"Annuler": function (){
				$(this).dialog('close');
			},
			"Valider": function (){
				newFactureFournisseur();
			}
		}
		
	});
	$('textarea.tinymce').tinymce({
		script_url : '/public/javascript/tinymce/jscripts/tiny_mce/tiny_mce.js',
		theme : "simple"
	});
	
	$('#t_facture').fixheadertable({
		colratio: [50,,120,120,100],
		zebra : true,
		sortable: true,
		sortType : ['integer','string','date','integer','string'],
		pager: true,
		rowsPerPage: 25
	});
	$('#t_paiements').fixheadertable({
		colratio: [50,,120,120,40],
		zebra : true,
		sortable: true,
		sortType : ['integer','string','date','integer','string'],
		pager: true,
		rowsPerPage: 25
	});
	$("#facture_lines").fixheadertable({
		sortable: false,
		pager: false,
		rowsPerPage: 10,
		colratio: ['',100,100,100,100,150]
	});
	$("#carnetAddress").fixheadertable({
		colratio: [50,200,''],
		zebra : true,
		sortable: true,
		sortType : ['string','string','string'],
		pager: true,
		rowsPerPage: 25
	});
	$(".datepicker").datepicker({
		dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
		monthNames: ['Janvier','F"vrier','Mars','Avril','Mai','Juin','Juillet','Aout','Septembre','Octobre','Novembre','Decembre'],
		dayNamesMin: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
		dateFormat: 'dd-mm-yy'
	});
	$("#preview").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		width: '700px',
		buttons: {
			"Fermer": function (){
				$(this).dialog('close');
			}
		}
	});
});
function round(val){
	return (Math.round((val*100))/100);
}
function calc_line(i){
	if(i){
		var qte = $("#qte_"+i).val();
		var montant = $("#ttc_"+i).val();
		var tva = $("#tva_"+i+" :selected").text();
		tva = parseFloat(tva.replace("%",""));
		
		$("#montant_ttc_"+i).val((qte*montant)+" €");		
		
	}
	
	var tot_ht = 0;
	var tot_55 = 0;
	var tot_196 = 0;
	var tot_ttc = 0;
	var a_payer = 0;
	for(var n=1 ; n<=20 ; n++){
		q = parseFloat($("#qte_"+n).val());
		m = parseFloat($("#ttc_"+n).val());
		if(!isNaN(q) && !isNaN(m)){
			tot_ttc += (q * m);
			t = $("#tva_"+n+" :selected").text();
			t = parseFloat(t.replace("%",""));
			if(t == 5.5){
				tot_55 += round((m-((q * m) / 1.055)));
			}else if(t == 19.6){
				tot_196 += round((m-((q * m) / 1.196)));
			}
		}
	}
	tot_ht = round(tot_ttc - tot_55 - tot_196);
	$("#tot_ht").html(tot_ht+" &euro;");
	$("#montant_55").html(tot_55+" &euro;");
	$("#montant_196").html(tot_196+" &euro;");
	
	a_payer = tot_ttc;
	
	$("#tot_ttc").html(tot_ttc+" &euro;");
	$("#a_payer").html(a_payer + " &euro;");
	// input hidden
	$("input[name=montant_ht]").val(tot_ht);
	$("input[name=montant_ttc]").val(tot_ttc);
	$("input[name=montant_55]").val(tot_55);
	$("input[name=montant_196]").val(tot_196);
}
function newFactureFournisseur(){
	var postVars = $("#new_facture_form").serializeArray();
	$.ajax({
        type: "POST",
        url: '/achats/xhr/newFactureFournisseur',
        dataType: "json",
        data: postVars,
        success: function(data){
        	if(data.response_code == "ok"){
        		if($("#facture_id").val() != ""){
        			$("#newFactureOK_dial").html("Facture mise à jour");
        		}else{
        			$("#newFactureOK_dial").html("Nouvelle facture enregistrée");
        		}
        		$("#newFactureOK_dial").dialog('open');
        	}else{
        		alert("Une erreur est survenue");
        	}
        }
	});
}
function removeFactureFournisseur(id){
	if(confirm("Supprimer la facture?")){
		$.ajax({
	        type: "POST",
	        url: '/achats/xhr/removeFactureFournisseur/'+id,
	        dataType: "json",
	        success: function(data){
	        	if(data.response_code == "ok"){
	        		window.location = "/achats?factures";
	        	}else{
	        		alert("Une erreur est survenue");
	        	}
	        }
		});
	}
}
function enregistrerPaiementFournisseur(facture_id){
	if(confirm("Enregistrer le paiement de la facture?")){
		$.ajax({
	        type: "POST",
	        url: '/achats/xhr/enregistrerPaiementFournisseur/'+facture_id,
	        dataType: "json",
	        success: function(data){
	        	if(data.response_code == "ok"){
	        		window.location = "/achats?paiements";
	        	}else{
	        		alert("Une erreur est survenue");
	        	}
	        }
		});
	}
}
function removePaiementFournisseur(facture_id){
	if(confirm("Supprimer le paiement de la facture?")){
		$.ajax({
	        type: "POST",
	        url: '/achats/xhr/removePaiementFournisseur/'+facture_id,
	        dataType: "json",
	        success: function(data){
	        	if(data.response_code == "ok"){
	        		window.location = "/achats?paiements";
	        	}else{
	        		alert("Une erreur est survenue");
	        	}
	        }
		});
	}
}
function editFactureFournisseur(id){
	$.ajax({
        type: "POST",
        url: '/achats/factureFournisseur/get/'+id,
        dataType: "json",
        success: function(data){
        	$("input[name=date]").val(data.date);
        	$("input[name=echeance]").val(data.echeance);
        	var name = "#option_type_reglement_"+data.type_reglement;
        	$(name).attr("selected",true);
        	$("input[name=ref_commande]").val(data.ref_commande);
        	$("#contact_"+data._fournisseur).attr("checked",true);
        	var n = 1;
        	for(var i in data.lines){
        		console.log(data.lines[i]);
        		$("#desc_"+n).text(data.lines[i].description);
        		$("#qte_"+n).val(data.lines[i].qte);
        		$("#ttc_"+n).val(data.lines[i].montant_ttc);
        		name = "#option_plan_"+n+"_"+data.lines[i].classe;
            	$(name).attr("selected",true);
            	name = "#option_tva_"+n+"_"+data.lines[i].taux_tva;
            	$(name).attr("selected",true);
        		calc_line(n);
        		n++;
        	}
        	calc_line();
        	$("#facture_id").val(data._id);
        	$('#new_facture_dial').dialog('open');
        }
	});
}
function previewFacture(id){
	$.ajax({
        type: "POST",
        url: '/preview/factureFournisseur/'+id,
        dataType: "html",
        success: function(data){
        	$("#preview").html(data);
        	$("#preview").dialog('open');
        }
	});
}